import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:joyagoo/config/app_colors.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/JoyBlocUtil.dart';
import '../utils/route_utils.dart';
import 'joy_home_bloc.dart';

class JoyLoginPage extends StatefulWidget {
  const JoyLoginPage({Key? key}) : super(key: key);

  @override
  State<JoyLoginPage> createState() => _JoyLoginPageState();
}

class _JoyLoginPageState extends State<JoyLoginPage> {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _isPasswordVisible = false;
  bool _isUserAgreementChecked = false;
  bool _isPrivacyAgreementChecked = false;
  bool _isLoading = false;

  late JoyHomeBloc loginBloc;

  @override
  void dispose() {
    _emailController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  // 验证邮箱格式
  bool _isValidEmail(String email) {
    return RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email);
  }

  // 验证密码不为空
  bool _isValidPassword(String password) {
    return password.trim().isNotEmpty;
  }

  // 显示提示消息
  void _showSnackBar(String message, {bool isError = false}) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: isError ? Colors.red : const Color(0xFFFF6B35),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
      ),
    );
  }

  // 登录/注册处理
  Future<void> _handleLogin() async {
    final email = _emailController.text.trim();
    final password = _passwordController.text;

    // 验证邮箱格式
    if (!_isValidEmail(email)) {
      _showSnackBar('Please enter a valid email format', isError: true);
      return;
    }

    // 验证密码不为空
    if (!_isValidPassword(password)) {
      _showSnackBar('Please enter password', isError: true);
      return;
    }

    // 检查协议是否勾选
    if (!_isUserAgreementChecked || !_isPrivacyAgreementChecked) {
      _showSnackBar('Please read and agree to the User Agreement and Privacy Policy first', isError: true);
      return;
    }



    loginBloc.add(PostJOYUserLoginEvent(context,email,password));


    // try {
    //   // 模拟网络请求延迟
    //
    //   // 保存登录信息
    //
    //   _showSnackBar('登录成功！');
    //
    //   // 延迟一下再跳转，让用户看到成功提示
    //   await Future.delayed(const Duration(milliseconds: 500));
    //
    //   // 返回上一页或跳转到主页
    //   if (Navigator.canPop(context)) {
    //      JoyNavUtils().back(result: "successful");
    //   } else {
    //      // 跳转到主页
    //      JoyNavUtils().back(result: "successful");
    //   }
    // } catch (e) {
    //   _showSnackBar('登录失败，请重试', isError: true);
    // } finally {
    //   setState(() {
    //     _isLoading = false;
    //   });
    // }
  }

  // 显示协议对话框
  void _showAgreementDialog(String title, String content) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        title: Text(
          title,
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.bold,
            color: const Color(0xFFFF6B35),
          ),
        ),
        content: SizedBox(
          width: double.maxFinite,
          height: 300.h,
          child: SingleChildScrollView(
            child: Text(
              content,
              style: TextStyle(
                fontSize: 14.sp,
                height: 1.5,
              ),
            ),
          ),
        ),
        actions: [
          ElevatedButton(
            onPressed: () => Navigator.pop(context),
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFFFF6B35),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
            child: Text(
              'I have read',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: AppColors.backHomeYellowGround,
        elevation: 0,
        leading: GestureDetector(
          onTap: () => Navigator.pop(context),
          child: Container(
            margin: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
            width: 40.w,
            height: 40.w,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 8,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: Icon(
              Icons.arrow_back_ios_new,
              color: AppColors.primaryVariant,
              size: 18.sp,
            ),
          ),
        ),
        title: Text(
          'Login/Register',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        centerTitle: true,
      ),
      body:BLocLogin()
    );
  }

  Widget BLocLogin(){
    return JoyBlocUtil.getAppNoBarBloc(builder: (context, state) {
      return loginView();
    }, create: (_) {
      loginBloc = JoyHomeBloc();

      return loginBloc;
    }, buildWhen: (previousState, state) {
      if(state is postUserLoginEventSuccess){
        final email = _emailController.text.trim();
        final password = _passwordController.text;
        String token = state.data;
        saveUserInfo(email,password,token);

        return true;
      }
      if(state is postUserLoginEventFailure){

        // 显示登录失败弹窗
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('Login failed, please check your email and password'),
            backgroundColor: Colors.red,
          ),
        );
        return true;
      }

      return false;
    });
  }

  Future<void> saveUserInfo(String email,String password,String token) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('isLoggedIn', true);
    await prefs.setString('userAccount', email);
    await prefs.setString('token', token);
    await prefs.setString('userPassword', password);
    await prefs.setString('loginTime', DateTime.now().toIso8601String());
    JoyNavUtils().back(result: "successful");

  }

  Widget showLogoAndNotice(){
    return Container(
      padding: EdgeInsets.only(left: 16.w,right: 16.w),
      child: Column(
        children: [
          Center(
            child: Column(
              children: [
                Container(
                  width: 60.w,
                  height: 60.w,
                  decoration: BoxDecoration(
                    color: AppColors.backHomeYellowGround,
                    borderRadius: BorderRadius.circular(30.r),
                  ),
                  child: Image.asset("images/icon_Vector.png"),
                ),
                SizedBox(height: 12.h),
                Text(
                  'LitBuy Sheets',
                  style: TextStyle(
                    fontSize: 24.sp,
                    fontWeight: FontWeight.bold,
                    color: AppColors.primaryVariant,
                  ),
                ),
                
              ],
            ),
          ),
          SizedBox(height: 12.h),
          // 提示文字
          Container(
            padding: EdgeInsets.all(12.w),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10.r),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
               Container(
                 width:15.w,
                 height: 15.w,
                 child: Image.asset("images/icon_notice.png"),
               ),
                SizedBox(width: 6.w),
                Expanded(
                  child: Text(
                    'Registration and login are on the same page, if you don\'t have an account, it will be created automatically',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: AppColors.primaryVariant,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }


  Widget showInputShow(){
    return Container(
      padding: EdgeInsets.only(left: 16.w,right: 16.w),

      child: Column(
        children: [
          SizedBox(height: 6.h),
          TextField(
            style: TextStyle(
              color: Colors.black,
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
            ),
            controller: _emailController,
            keyboardType: TextInputType.emailAddress,
            decoration: InputDecoration(
              hintText: 'Please enter email address',
              hintStyle: TextStyle(fontSize: 14.sp,color: AppColors.garyVariant),
              prefixIcon: Icon(
                Icons.email_outlined,
                color: Colors.grey[400],
                size: 18.sp,
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.r),
                borderSide: BorderSide(color: Colors.grey[300]!),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.r),
                borderSide: const BorderSide(color: Color(0xFFFF6B35)),
              ),
              filled: true,
              fillColor: Colors.grey[50],
              contentPadding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
            ),
          ),
          SizedBox(height: 16.h),

          // 密码输入框

          SizedBox(height: 6.h),
          TextField(
            style: TextStyle(
              color: Colors.black,
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
            ),
            controller: _passwordController,
            obscureText: !_isPasswordVisible,
            decoration: InputDecoration(
              hintText: 'Please enter password',
              hintStyle: TextStyle(fontSize: 14.sp,color: AppColors.garyVariant),
              prefixIcon: Icon(
                Icons.lock_outline,
                color: Colors.grey[400],
                size: 18.sp,
              ),
              suffixIcon: IconButton(
                icon: Icon(
                  _isPasswordVisible ? Icons.visibility : Icons.visibility_off,
                  color: Colors.grey[400],
                  size: 18.sp,
                ),
                onPressed: () {
                  setState(() {
                    _isPasswordVisible = !_isPasswordVisible;
                  });
                },
              ),
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.r),
                borderSide: BorderSide(color: Colors.grey[300]!),
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(10.r),
                borderSide: const BorderSide(color: Color(0xFFFF6B35)),
              ),
              filled: true,
              fillColor: Colors.grey[50],
              contentPadding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.h),
            ),
          ),
          SizedBox(height: 20.h),

          // 协议勾选
          Row(
            children: [
              Checkbox(
                fillColor: MaterialStateProperty.resolveWith((states) {
                  if (states.contains(MaterialState.selected)) {
                    return AppColors.primaryVariant; // 选中时的填充色
                  }
                  // 未选中时的填充色（默认透明，可改为其他颜色）
                  return Color(0xFFD9DADB);
                }),
                value: _isUserAgreementChecked && _isPrivacyAgreementChecked,
                onChanged: (value) {
                  setState(() {
                    _isUserAgreementChecked = value ?? false;
                    _isPrivacyAgreementChecked = value ?? false;
                  });
                },
                activeColor: AppColors.primaryVariant,
              ),
              Expanded(
                child: RichText(
                  text: TextSpan(
                    style: TextStyle(
                      fontSize: 11.sp,
                      color: Colors.grey[600],
                    ),
                    children: [
                      TextSpan(text: 'I have read and agree to the '),
                      TextSpan(
                          text: 'User Agreement',
                          style: TextStyle(
                            color: const Color(0xFFFF6B35),
                            decoration: TextDecoration.underline,
                          ),
                          recognizer: TapGestureRecognizer()
                            ..onTap = () {

                            }
                      ),
                      TextSpan(text: ' and '),
                      TextSpan(
                          text: 'Privacy Policy',
                          style: TextStyle(
                            color: const Color(0xFFFF6B35),
                            decoration: TextDecoration.underline,
                          ),
                          recognizer: TapGestureRecognizer()
                            ..onTap = (){

                            }
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),

          // 登录按钮
          SizedBox(
            width: double.infinity,
            height: 44.h,
            child: ElevatedButton(
              onPressed: _isLoading ? null : _handleLogin,
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.primaryVariant,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10.r),
                ),
                elevation: 0,
              ),
              child: _isLoading
                  ? SizedBox(
                width: 18.w,
                height: 18.w,
                child: const CircularProgressIndicator(
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  strokeWidth: 2,
                ),
              )
                  : Text(
                'Login/Register',
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                ),
              ),
            ),
          ),
          SizedBox(height: 20.h),

          // 底部提示
          Center(
            child: Text(
              'By logging in, you agree to our terms of service and privacy policy',
              style: TextStyle(
                fontSize: 10.sp,
                color: Colors.grey[500],
              ),
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
    );
  }




  Widget loginView(){
    return SingleChildScrollView(
       // padding: EdgeInsets.all(24.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Logo 和欢迎文字
          Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(bottomLeft:Radius.circular(10.w),bottomRight:Radius.circular(10.w) ),
                  color: AppColors.backHomeYellowGround,
                ),
                height: 170,
              ),
              showLogoAndNotice()
            ],
          )
          ,

          SizedBox(height: 16.h),
          showInputShow(),
          // 邮箱输入框

        ],
      ),
    );
  }
}